/*
 * File:   main.cpp
 * Author: foxss
 */
#include "easyconnect.h"
#include "UIManager.h"
#include "Peer.h"

PSP_MODULE_INFO("VersiPSP", 0, 1, 1);
PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER | THREAD_ATTR_VFPU);
PSP_HEAP_SIZE_KB(20*1024);

EasyConnect connection;
TiXmlDocument* doc;
UIManager myUIManager;

/* Exit callback */
int exit_callback(int arg1, int arg2, void *common) {
    return 0;
}

/* Callback thread */
int CallbackThread(SceSize args, void *argp) {
    int cbid;
    cbid = sceKernelCreateCallback("Exit Callback", exit_callback, NULL);
    sceKernelRegisterExitCallback(cbid);
    sceKernelSleepThreadCB();
    return 0;
}

/* Sets up the callback thread and returns its thread id */
int SetupCallbacks(void) {
    int thid = 0;
    thid = sceKernelCreateThread("update_thread", CallbackThread, 0x11, 0xFA0, PSP_THREAD_ATTR_USER, 0);
    if(thid >= 0)
        sceKernelStartThread(thid, 0, 0);
    return thid;
}

bool LoadMenu(){
  curl_global_init(CURL_GLOBAL_ALL);
  Peer menu("http://socketpsp.googlecode.com/files/menu1.xml","menu1.xml");
  menu.runprogress();
  doc = new TiXmlDocument("menu1.xml");
  if(doc && !doc->Error()){
    return doc->LoadFile();
  }else{
    delete doc;
    return false;
  }
}

int main() {
    SetupCallbacks();
    connection.InitGU();
    connection.Connect();
    connection.TermGU();

    if (connection.IsConnected()) {
        myUIManager.load();
        if(!LoadMenu() || !myUIManager.ParseDoc(doc)){
            sceKernelExitGame();
            return 0;
        }

        int _skip = 1;
        while(!osl_quit){
           if (!_skip){
               oslStartDrawing();
               myUIManager.run();
               oslDrawStringf(300, 10,"%f",progress);
               oslEndDrawing();
           }
           oslEndFrame();
           _skip = oslSyncFrame();
        }

        myUIManager.unload();
        delete doc;
    }
    sceKernelExitGame();
    return 0;
}
